package com.soen6441.generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

class TypeSafeGenericAlgorithms {
    static class A {};
    static class B extends A {};
    static class C extends B {};

    static int count(Iterable<?> container){
        int result = 0;
        for(Object obj : container){
            result++;
        }
        return result;
    }

    static <T> void copy(Collection<? extends T> source,
                         Collection<? super T> destination){
        for(T t: source){
            destination.add(t);
        }
    }

    static double max(Iterable<? extends Number> nums){
        double maxNum = Double.MIN_VALUE;
        for(Number num : nums){
            maxNum = Math.max(maxNum, num.doubleValue());
        }
        return maxNum;
    }


    public static void main(String[] args) {
        ArrayList<Integer> ints
                = new ArrayList<Integer>(Arrays.asList(31, 7, 42, 37));

        ArrayList<Double> doubles =
                new ArrayList<Double>( Arrays.asList(9.98, 3.0e8, 3.14));

        System.out.println(count(ints)); // 4;
        System.out.println(count(doubles)); // 3
        System.out.println((int)max(ints)); // 42
        System.out.println(max(doubles)); // 3.0e8

        ArrayList<A> as = new ArrayList<A>();
        ArrayList<B> bs = new ArrayList<B>();
        ArrayList<C> cs = new ArrayList<C>();

        // ok C is an A
        copy(cs, as);
        // ok C is an A
        copy(bs, as);
        // ok C is a B
        copy(cs, bs);

        //copy(as, bs); // won't compile A is not a B
        //copy(bs, cs); // won't compile B is not a C
    }
}
